package com.ms.base.comm.error;

import com.ms.base.comm.util.FrameUtil;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;

/**
 * <b>description</b>： <br>
 * <b>time</b>：2018-07-31 14:05 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class GlobalErrorController extends BasicErrorController {

    private GlobalErrorConfigProperties globalErrorConfigProperties;

    public GlobalErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, GlobalErrorConfigProperties globalErrorConfigProperties) {
        super(errorAttributes, errorProperties);
        this.globalErrorConfigProperties = globalErrorConfigProperties;
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        return new ResponseEntity<>(body, HttpStatus.OK);
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        if (this.globalErrorConfigProperties != null && this.globalErrorConfigProperties.getWebType() == WebType.API) {
            HttpStatus status = getStatus(request);
            Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
                    request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            try {
                response.getWriter().write(FrameUtil.json(model));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        } else {
            return super.errorHtml(request, response);
        }
    }
}
